﻿using System;
using System.Diagnostics;
using System.IO;
using System.Threading;

namespace MangosRestarter
{
    /// <summary>
    /// MySQL启动器
    /// </summary>
    internal static class MySqlStarter
    {
        private const int StartupTimeoutMs = 15000; // 15秒超时

        /// <summary>
        /// 使用CMD启动MySQL并显示控制台，返回启动的cmd进程
        /// </summary>
        internal static bool TryStartWithVisibleConsole(out string error)
        {
            error = null;

            if (MySqlChecker.IsRunning())
                return true;

            var exe = ConfigHelper.MySqlPath;
            if (!Path.IsPathRooted(exe))
                exe = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, exe);

            if (!File.Exists(exe))
            {
                error = $"MySQL 可执行文件不存在：{exe}";
                return false;
            }

            Process proc = null;
            try
            {
                string mysqlDirectory = Path.GetDirectoryName(exe);
                string mysqlExe = Path.GetFileName(exe);

                string arguments = $"/k \"color 0A && cd /d \"{mysqlDirectory}\" && title MySQL Server && echo. && echo [MySQL启动中...] && echo. && echo. && {mysqlExe} {ConfigHelper.MySqlArgs}\"";

                Logger.Write($"启动MySQL并设置绿色控制台: {arguments}");

                var psi = new ProcessStartInfo
                {
                    FileName = "cmd.exe",
                    Arguments = arguments,
                    UseShellExecute = true,
                    CreateNoWindow = false,
                    WorkingDirectory = mysqlDirectory
                };

                proc = Process.Start(psi);

                DateTime startTime = DateTime.Now;
                bool started = false;

                while ((DateTime.Now - startTime).TotalMilliseconds < StartupTimeoutMs)
                {
                    if (MySqlChecker.IsRunning())
                    {
                        Logger.Write("MySQL 启动成功");
                        started = true;
                        break;
                    }
                    Thread.Sleep(500);
                }

                if (started) return true;

                error = "MySQL启动超时";
                return false;
            }
            catch (Exception ex)
            {
                error = "启动异常：" + ex.Message;
                try { proc?.Kill(); } catch { }
                return false;
            }
            finally
            {
                // 注意：这里不能dispose proc，因为cmd进程需要保持运行来托管MySQL
                // proc?.Dispose();
            }
        }
    }
}